package com.rui.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.locks.ReentrantLock;

@SuppressWarnings("all")
//CAS 比较并交换
public class CASDemo {
    public static void main(String[] args) {
//        AtomicInteger atomicInteger = new AtomicInteger(2020);

        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(2020,1);

        new Thread(() -> {
            int sample = atomicStampedReference.getStamp();
            System.out.println("a1 =>" + sample);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ReentrantLock reentrantLock = new ReentrantLock();

            System.out.println(atomicStampedReference.compareAndSet(2020, 2022, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("a2 =>" + atomicStampedReference.getStamp());
            System.out.println(atomicStampedReference.compareAndSet(2022, 2020, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("a3 =>" + atomicStampedReference.getStamp());
        },"a").start();

        new Thread(() -> {
            int sample = atomicStampedReference.getStamp();
            System.out.println("b1 =>" + sample);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicStampedReference.compareAndSet(2020, 6666, sample, sample + 1));
            System.out.println("b2 => " + sample);
        },"b").start();
    }
}
